/*
 * @author zzr
 * @date: 2025/05/09  20:35
 * @description: 完整的自己实现一个 Timer 计时器
 */

import java.util.PriorityQueue;

class MyTimerTask2 implements Comparable<MyTimerTask2>{

    private long time;
    private Runnable runnable;
    Object locker = new Object();

    public MyTimerTask2(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask2 o) {
        return (int) (this.time - o.time);
    }
}
class MyTimer2 {

    private Thread thread;
    private PriorityQueue<MyTimerTask2> queue = new PriorityQueue<>();
    private Object locker = new Object();
    private long curTime;
    public void schedule (Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask2 myTimerTask2 = new MyTimerTask2(runnable, delay);
            queue.offer(myTimerTask2);
            locker.notify();
        }
    }
    public MyTimer2() {
        thread = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    try {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask2 task = queue.peek();
                        curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {
                            queue.poll();
                            task.run();
                        } else {
                            locker.wait(task.getTime() - curTime);
                            curTime = System.currentTimeMillis();
                            if (curTime >= task.getTime()) {
                                queue.poll();
                                task.run();
                            }
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        thread.start();
    }
}
public class Demo9 {
    public static void main(String[] args) {
        int flg = 0;
        MyTimer2 myTimer2 = new MyTimer2();
        myTimer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);

    }
}
